package com.osfw.framework.utils;

import com.baomidou.mybatisplus.annotation.TableField;
import com.github.pagehelper.PageHelper;
import com.osfw.framework.annotation.FieldMapping;
import com.osfw.framework.core.page.PageDomain;
import com.osfw.framework.core.page.TableSupport;
import com.osfw.framework.exception.ServiceException;
import com.osfw.framework.utils.sql.SqlUtil;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Field;

/**
 * 分页工具类
 */
@Slf4j
public class PageUtils extends PageHelper {
    /**
     * 设置请求分页数据
     */
    public static void startPage(Class clz) {
        PageDomain pageDomain = TableSupport.buildPageRequest();
        Integer pageNum = pageDomain.getPageNum();
        Integer pageSize = pageDomain.getPageSize();
        String orderBy = SqlUtil.escapeOrderBySql(pageDomain.getOrderBy());
        if(StringUtils.isNotEmpty(orderBy)) {
            try {
                Field orderByField = clz.getField(orderBy);
                if (orderByField.isAnnotationPresent(TableField.class)) {
                    TableField tableFieldAnn = orderByField.getAnnotation(TableField.class);
                    if (tableFieldAnn != null && tableFieldAnn.value().length() > 0) {
                        orderBy = tableFieldAnn.value();
                    }
                }
            } catch (NoSuchFieldException e) {
                log.error("实体不存在该排序属性");
            }
        }
        Boolean reasonable = pageDomain.getReasonable();
        PageHelper.startPage(pageNum, pageSize, orderBy).setReasonable(reasonable);
    }

    /**
     * 清理分页的线程变量
     */
    public static void clearPage() {
        PageHelper.clearPage();
    }
}
